package com.shen.eduservice.listener;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.shen.eduservice.entity.EduSubject;
import com.shen.eduservice.entity.excel.ExcelSubjectData;
import com.shen.eduservice.service.EduSubjectService;
import com.shen.exceptionHandler.GuliException;

public class SubjectExcelListener extends AnalysisEventListener<ExcelSubjectData> {
    //没写注解 --没交给spring 管理（listener 我们手动new ） 没法自动注入-- 不能实现数据库操作
    public EduSubjectService eduSubjectService;

    @Override
    public void invoke(ExcelSubjectData excelSubjectData, AnalysisContext analysisContext) {
        if(excelSubjectData==null){
            throw  new GuliException(20001,"文件为空");
        }
        EduSubject existOneSubject = this.existOneSubject(eduSubjectService, excelSubjectData.getOneSubjectName());
        if(existOneSubject==null){
            existOneSubject =new EduSubject();
            existOneSubject.setParentId("0");
            existOneSubject.setTitle(excelSubjectData.getOneSubjectName());

                eduSubjectService.save(existOneSubject);
        }
        String pid=existOneSubject.getId();
        EduSubject existTwoSubject = this.existTwoSubject(eduSubjectService, excelSubjectData.getTwoSubjectName(), pid);
        if(existTwoSubject==null){
            existTwoSubject =new EduSubject();
            existTwoSubject.setTitle(excelSubjectData.getTwoSubjectName());
            existTwoSubject.setParentId(pid);
            eduSubjectService.save(existTwoSubject);

        }


    }
    //判断一级分类 不能重复
    private EduSubject existOneSubject(EduSubjectService eduSubjectService,String name){
        QueryWrapper<EduSubject>  wrapper =new QueryWrapper<>();
        wrapper.eq("title",name);
        wrapper.eq("parent_id","0");
        EduSubject subject = eduSubjectService.getOne(wrapper);
        return subject;
    }
    //判断二级分类 不能重复
    private EduSubject existTwoSubject(EduSubjectService eduSubjectService,String name,String pid){
        QueryWrapper<EduSubject>  wrapper =new QueryWrapper<>();
        wrapper.eq("title",name);
        wrapper.eq("parent_id",pid);
        EduSubject subject = eduSubjectService.getOne(wrapper);
        return subject;
    }

    public SubjectExcelListener(EduSubjectService eduSubjectService) {
        this.eduSubjectService = eduSubjectService;
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext analysisContext) {

    }
}
